package com.apobates.forum.thrones.controller;

import com.apobates.forum.core.entity.Topic;
import com.apobates.forum.core.service.TopicService;
import com.apobates.forum.event.elderly.ForumActionEnum;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import com.apobates.forum.thrones.controller.helper.OnlineDescriptor;
import com.apobates.forum.utils.FrontPageURL;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.PageRequest;
import com.apobates.forum.utils.persistence.Pageable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 搜索控制器
 *
 * @author xiaofanku
 * @since 20200526
 */
@Controller
@RequestMapping(value = "/search")
public class TopicSearchController {
    @Autowired
    private TopicService topicService;
    @Value("${site.pageSize}")
    private int pageSize;
    
    @GetMapping(path = "/")
    @OnlineDescriptor(action=ForumActionEnum.TOPIC_SEARCH)
    public String searchHome(
            @RequestParam("word") String searchWord,
            @RequestParam(value = "token", required = false, defaultValue = "0") String token,
            @RequestParam(value = "p", required = false, defaultValue = "1") int page,
            MemberSessionBean mbean,
            HttpServletRequest request,
            Model model) {
        List<String> sw = Optional.ofNullable(searchWord).map(str->Arrays.asList(str.split(" "))).orElse(Collections.emptyList());
        String topicLink = String.format("%s/search/", request.getContextPath());
        FrontPageURL fpbuild = new FrontPageURL(topicLink).addPageSize("number", pageSize).addParameter("word", searchWord);
        Pageable pr = new PageRequest(page, fpbuild.getPageSize());
        
        Page<Topic> rs = topicService.getAllForTag(sw, pr);
        model.addAttribute("rs", rs.getResult().collect(Collectors.toList()));
        model.addAttribute("pageData", fpbuild.toPageData(pr, rs.getTotalElements()));//pr.toData(fpbuild, rs.getTotalElements()));
        model.addAttribute("pageTitle", "话题搜索 p" + page);
        return "default/search/index";
    }
}